<?php
namespace modules\post;
use \modules\auth\api as auth;
use \phiction\exceptions\bad_request;
use \phiction\array_utils as arr;

class api
{
    static function list($q, &$args): array
    {
        $page = arr::get_or_bad_request($args, 'page');
        return storage::list($q, $page)->run();
    }

    static function fetch($q, &$args)
    {
        $id = arr::get_or_bad_request($args, 'id');
        return storage::fetch($q, $id)->run();
    }

    static function add($q, &$args)
    {
        $title = arr::get_or_bad_request($args, 'title');
        $body  = arr::get_or_bad_request($args, 'body');

        $shards = auth::validate_with_role($q, $args, 'admin');
        $author = $shards['id'];

        if (storage::add($q, $title, $body, $author)->run() !== 1)
            throw new bad_request("cannot post article");
    }

    static function delete($q, &$args)
    {
        $id = (int)arr::get_or_bad_request($args, 'id');
        auth::validate_with_role($q, $args, 'admin');
        if (storage::delete($q, $id)->run() !== 1)
            throw new bad_request("cannot delete article #$id");
    }

    static function edit($q, &$args)
    {
        $id = (int)arr::get_or_bad_request($args, 'id');
        $title = arr::get_or_bad_request($args, 'title');
        $body  = arr::get_or_bad_request($args, 'body');

        auth::validate_with_role($q, $args, 'admin');

        if (storage::edit($q, $id, $title, $body)->run() !== 1)
            throw new bad_request("cannot edit article #$id");
    }
}

